package com.haizhi.vp.utils;

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
public class GenWordUtil {
    /**
     * 填写word
     *
     * @param sourceUrl 模板的位置
     * @param params    参数
     */
    public static void genWord(Document document, String sourceUrl, Map<String, String> params) {
        log.info("开始通过模板组装word,模板的位置{},传递的参数{}", sourceUrl, params);

        document.loadFromFile(sourceUrl);
        replaceSpecialWord(document, params);
        log.info("结束生成word");
    }


    /**
     * 替换Word文件中 ${} 标识的特殊字符
     * <br>
     * <strong>注意：如果存在部分特殊表示无法替换，请尝试将 ${} 的整个字符串复制到word中，有可能word没有将${}识别为一个整体</strong>
     *
     * @param doc: Sprire Document
     * @param map: 占位符${} 与 需要替换的为字符串的对应关系
     */
    private static void replaceSpecialWord(Document doc, Map<String, String> map) {
        // 正则表达式，匹配所有的占位符 ${}
        Pattern pattern = Pattern.compile("\\$\\{.*?}");
        // 根据正则表达式获取所有文本
        TextSelection[] allPattern = doc.findAllPattern(pattern);
        // 逐个替换占位符
        for (TextSelection textSelection : allPattern) {
            String tmp = map.get(textSelection.getSelectedText());
            System.out.print(textSelection.getSelectedText());
            int res = doc.replace(textSelection.getSelectedText(), tmp, true, true);
            System.out.println(": " + res);
        }
    }


    // 创建段落
    public static void createText(Section section, String text) {
        //      创建一个段落，添加一些信息 一、查询需求：
        Paragraph paragraph = section.addParagraph();

        TextRange tr = paragraph.appendText(text);
        tr.getCharacterFormat().setFontSize(16);
        tr.getCharacterFormat().setTextColor(Color.darkGray);
        tr.getCharacterFormat().setFontName("方正仿宋_GBK");

        paragraph.getFormat().setBeforeAutoSpacing(false);
        paragraph.getFormat().setBeforeSpacing(5);
        paragraph.getFormat().setFirstLineIndent(30);
    }

    // 创建段落
    public static void createTitle(Section section, String text) {
        //      创建一个段落，添加一些信息 一、查询需求：
        Paragraph paragraph = section.addParagraph();

        TextRange tr = paragraph.appendText(text);
        tr.getCharacterFormat().setFontSize(16);
//        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setTextColor(Color.BLACK);
        tr.getCharacterFormat().setFontName("方正黑体_GBK");

        paragraph.getFormat().setBeforeAutoSpacing(false);
        paragraph.getFormat().setBeforeSpacing(5);
        paragraph.getFormat().setFirstLineIndent(30);
    }


    // 动态创建表格
    public static void createDoc(Section section, List<String> header, List<List<Object>> data) {
        //添加表格
        Table table = section.addTable(true);
        //设置表格的行数和列数
        table.resetCells(data.size() + 1, header.size());
        table.getTableFormat().isAutoResized(false);

        //设置第一行作为表格的表头并添加数据
        TableRow row = table.getRows().get(0);
        table.autoFit(AutoFitBehaviorType.Fixed_Column_Widths);
        table.getTableFormat().setHorizontalAlignment(RowAlignment.Center);
        row.isHeader(true);
        row.setHeight(48);
        row.setHeightType(TableRowHeightType.Auto);
        table.getTableFormat().isBreakAcrossPages(true);
        table.getTableFormat().setWrapTextAround(false);

//        TableRow row3 = table.getRows().get(0);
//        row3.isHeader(true);
//        row3.setHeight(60);
//        row3.setHeightType(TableRowHeightType.Exactly);
//        row3.getCells().get(0).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
//        table.applyHorizontalMerge(0, 0, header.size() - 1);


        for (int i = 0; i < header.size(); i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            p.getFormat().setKeepFollow(false);
//            p.getFormat().set
            TextRange range1 = p.appendText(header.get(i));
            range1.getCharacterFormat().setTextColor(Color.black);
            range1.getCharacterFormat().setFontName("方正仿宋_GBK");
            range1.getCharacterFormat().setFontSize(10);
        }

        //添加数据到剩余行
        try {
            for (int r = 0; r < data.size(); r++) {
                TableRow dataRow = table.getRows().get(r + 1);
                dataRow.setHeight(35);
                dataRow.setHeightType(TableRowHeightType.Auto);
                dataRow.getRowFormat().setBackColor(Color.white);
                dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center);
                for (int c = 0; c < data.get(r).size(); c++) {
                    dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                    String s = data.get(r).get(c).toString();
                    TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(s);
                    range2.getCharacterFormat().setFontName("方正仿宋_GBK");
                    range2.getCharacterFormat().setFontSize(10);
                    range2.getCharacterFormat().setTextColor(Color.darkGray);
                }
            }
        } catch (Exception e) {
            e.getMessage();
            log.info("插入数据有异常");
        }
        section.addParagraph();
    }


}
